#include "Log.hpp"
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace LogModule;

// 利用命令行参数
// ./udpclient server_ip server_port
int main(int argc,char* argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 1. 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket error!";
        exit(1);
    }
    LOG(LogLevel::INFO) << "socket success : " << sockfd;

    // 2. 给sockfd,绑定IP和端口号,OS自动绑定

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    inet_pton(AF_INET,server_ip.c_str(),&server.sin_addr);
    while (true)
    {
        // 1. 发消息
        std::string input;
        std::cout << "Please Enter# ";
        std::getline(std::cin, input); // 以\n为结束符

        sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr *)&server, sizeof(server));

        // 2. 收消息
        char buf[128];
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        socklen_t len = sizeof(addr);
        int s = recvfrom(sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&addr,&len);
        if(s > 0)
        {
            buf[s] = 0;
            std::cout << buf << std::endl;
        }
    }

    return 0;
}
